package com.qf.topic;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

public class Producer {
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        //rabbitmq服务器安装的机器IP
        factory.setHost("localhost");
        //rabbitmq通过amqp协议连接时的端口号
        factory.setPort(5672);
        factory.setUsername("guest");
        factory.setPassword("guest");
        //设置消息数据保存的虚拟主机,不同的虚拟主机彼此隔离
        factory.setVirtualHost("cdm");

        //获取connection对象
        Connection connection = factory.newConnection();
        //通过connection获取内部通道
        Channel channel = connection.createChannel();

        //声明交换机
        /*
            话题模式要求通配符路由键，所以交换机类型是：TOPIC
         */
        channel.exchangeDeclare("topicEx", BuiltinExchangeType.TOPIC);

        //声明2个队列
        channel.queueDeclare("topicQue1",true,false,false,null);
        channel.queueDeclare("topicQue2",true,false,false,null);

        //绑定交换机和队列的关系
        /*
            String queue: 队列名
            String exchange：交换机名
            String routingKey：路由键  TOPIC类型的交换机，需要指定通配符路由键
                        通配符：
                            * ： 表示有且只有一个单词
                            # ： 表示任意个单词（0或者多个）
         */
        channel.queueBind("topicQue1","topicEx","A.*");
        channel.queueBind("topicQue2","topicEx","A.#");

        //发送消息
        channel.basicPublish("topicEx","A",null,("我是rabbitmq发送的话题消息消息，路由键为A").getBytes(StandardCharsets.UTF_8));
        channel.basicPublish("topicEx","A.abc.def",null,("我是rabbitmq发送的话题消息消息，路由键为A.abc.def").getBytes(StandardCharsets.UTF_8));
        channel.basicPublish("topicEx","A.bbb",null,("我是rabbitmq发送的话题消息消息，路由键为A.bbb").getBytes(StandardCharsets.UTF_8));

        //释放资源
        channel.close();
        connection.close();
    }
}
